package com.davidk.survey.server;

import java.io.IOException;
import java.util.HashMap;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.davidk.survey.server.data.SurveyDAO;
import com.davidk.survey.server.model.Survey;
import com.davidk.survey.server.model.smartgwtrest.Response;
import com.davidk.survey.server.model.smartgwtrest.ErrorResponse;
import com.davidk.survey.server.model.smartgwtrest.FetchResponse;
import com.davidk.survey.server.service.SurveyService;
import com.google.inject.Inject;

@Controller
@RequestMapping("/survey")
public class SurveyController {

	private static SurveyDAO dao = new SurveyDAO();

	public static SurveyDAO getDao() {
		return dao;
	}

	@Inject
	public static void setDao(SurveyDAO dao) {
		if (SurveyController.dao == null)
			SurveyController.dao = dao;
	}

	HashMap<String, DataSourceInterface> dsMap = new HashMap<String, DataSourceInterface>();

	@ModelAttribute("response")
	@RequestMapping(value = "addApi", method = RequestMethod.POST)
	public Response addApi(@RequestBody SurveyAddRequest req, HttpServletRequest request) throws IOException {
		try {
			DataSourceInterface ds = dsMap.get(req.getDataSource());
			if (ds == null) {
				if (req.dataSource.startsWith("isc_SurveyDataSource")) {
					System.out.println("Creating DS " + req.getDataSource());
					ds = new SurveyDAO();
					dsMap.put(req.dataSource, ds);
				}
			}

			if (ds == null) {
				return new ErrorResponse(Response.STATUS_FAILURE, "Controller : Unable to get datasource : "
						+ req.getDataSource());
			}

			if (req.getOperationType().equals("add"))
				return ds.add(req, req.data);
			if (req.getOperationType().equals("update"))
				return ds.update(req, req.data);
			if (req.getOperationType().equals("remove"))
				return ds.remove(req, req.data);

			return new ErrorResponse(Response.STATUS_FAILURE, "Controller : Unable to execute operation : "
					+ req.getOperationType());
		} catch (Exception ex) {
			return new ErrorResponse(Response.STATUS_FAILURE, "Controller : Unknown Error : " + ex.getMessage());
		}
	}

	@ModelAttribute("response")
	@RequestMapping(value = "baseApi", method = RequestMethod.GET)
	public Response baseApi(HttpServletRequest request) throws IOException {
		try {
			DataRequest req = DataRequest.from(request);

			DataSourceInterface ds = dsMap.get(req.getDataSource());
			if (ds == null) {
				if (req.dataSource.startsWith("isc_SurveyDataSource")) {
					System.out.println("Creating DS " + req.getDataSource());
					ds = new SurveyDAO();
					dsMap.put(req.dataSource, ds);
				}
			}

			if (ds == null) {
				return new ErrorResponse(Response.STATUS_FAILURE, "Controller : Unable to get datasource : "
						+ req.getDataSource());
			}

			if (req.getOperationType().equals("fetch"))
				return ds.fetch(req);

			return new ErrorResponse(Response.STATUS_FAILURE, "Controller : Unable to execute operation : "
					+ req.getOperationType());
		} catch (Exception ex) {
			return new ErrorResponse(Response.STATUS_FAILURE, "Controller : Unknown Error : " + ex.getMessage());
		}

	}
	
	@RequestMapping(value = "getbyid", method = RequestMethod.GET)
	public Survey getSurvey(HttpServletRequest request) throws IOException {
		String ids = request.getParameter("id");
		try {
			long id = Long.parseLong(ids);

			if (id == 0)
				return SurveyService.getBlankSurvey();
			else
				return dao.fetch(id);
		} catch (NumberFormatException ex) {
		}
		return null;
	}

	@RequestMapping(value = "list", method = RequestMethod.GET)
	public Response getSurveyList(HttpServletRequest request) throws IOException {
		FetchResponse<Survey> ret = new FetchResponse<Survey>();
		ret.setData(dao.list());
		return ret;
	}

	@ModelAttribute("Survey")
	@RequestMapping(value = "save", method = RequestMethod.POST)
	public Survey saveSurvey(@RequestBody Survey survey, HttpServletRequest request) throws IOException {
		try {
			dao.save(survey);
		} catch (Exception ex) {
			throw new IOException("Datastore error, please try again later", ex);
		}
		return survey;
	}
}
